package com.csx.governance.traffic.core.interceptor.outbound;

import com.csx.governance.traffic.core.TransportableAttributes;
import com.csx.governance.traffic.core.context.TrafficRequest;
import com.csx.governance.traffic.core.context.TrafficResponse;
import org.springframework.core.Ordered;

import java.util.Map;

/**
 * 将 TransportableAttributes 中属性取出来，放入到 出站请求 的 attributes 和 headers 中
 * @author cuisongxu
 * @date 2023/4/2 13:20
 */
public class TransportAttributesTakeOutboundHandlerInterceptor extends TrafficAbstractOutboundHandlerInterceptor {

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 1000;
    }

    @Override
    public boolean preHandle(TrafficRequest request, TrafficResponse response) {
        Map<String, String> attributes = TransportableAttributes.getAttributes();
        // 设置到attributes中是为了在进行全链路灰度中泳道过滤器中取出swimLaneId(泳道ID),从而完成服务实例过滤
        attributes.forEach(request::setAttribute);
        // 设置到header中,这里会将请求头塞入到所有 原始请求 的header中,从而完成泳道ID传递到下一个请求中,从而完成全链路灰度
        attributes.forEach(request::setHeader);
        return super.preHandle(request, response);
    }
}
